package com.spzx.payment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.order.api.RemoteOrderInfoService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.mapper.PaymentInfoMapper;
import com.spzx.payment.service.IPaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 付款信息表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-11-21
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements IPaymentInfoService {
    @Autowired
    private RemoteOrderInfoService remoteOrderInfoService;

    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {

        //防止重复提交：如果支付日志已存在则直接返回
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));
        if (paymentInfo != null) {
            return paymentInfo;
        }
        //根据订单号获取订单信息
        R<OrderInfo> orderInfoResult = remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
        if (R.FAIL == orderInfoResult.getCode()) {
            throw new ServiceException(orderInfoResult.getMsg());
        }
        OrderInfo orderInfo = orderInfoResult.getData();

        paymentInfo = new PaymentInfo();

        paymentInfo.setUserId(orderInfo.getUserId());
        String content = orderInfo.getOrderItemList().stream()
                // 将每个 OrderItem 变换为其 SKU 名称
                // 使用空格连接所有 SKU 名称
                .map(OrderItem::getSkuName).collect(Collectors.joining(" "));

        paymentInfo.setContent(content);
        paymentInfo.setAmount(orderInfo.getTotalAmount());
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentStatus(0);
        baseMapper.insert(paymentInfo);

        return paymentInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePaymentStatus(Map<String, String> paramMap, Integer payType) {
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, paramMap.get("out_trade_no")));
        //已支付，直接返回
        if (paymentInfo.getPaymentStatus() == 1){
            return;
        }
        //未支付，更新支付信息
        paymentInfo.setPayType(payType);
        paymentInfo.setPaymentStatus(1);
        paymentInfo.setTradeNo(paramMap.get("trade_no"));
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSON.toJSONString(paramMap));
        baseMapper.updateById(paymentInfo);
    }
}
